package com.oracle.lingshangejia.activity;

import android.app.Activity;
import android.app.Dialog;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.support.v7.app.AlertDialog;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.baidu.ocr.sdk.OCR;
import com.baidu.ocr.sdk.OnResultListener;
import com.baidu.ocr.sdk.exception.OCRError;
import com.baidu.ocr.sdk.model.IDCardParams;
import com.baidu.ocr.sdk.model.IDCardResult;
import com.baidu.ocr.ui.camera.CameraActivity;
import com.baidu.ocr.ui.camera.CameraNativeHelper;
import com.baidu.ocr.ui.camera.CameraView;
import com.bumptech.glide.Glide;
import com.google.gson.Gson;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.entity.LocalMedia;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.Response;
import com.oracle.lingshangejia.Constant;
import com.oracle.lingshangejia.R;
import com.oracle.lingshangejia.base.BaseActivity;
import com.oracle.lingshangejia.bean.IdCardBean;
import com.oracle.lingshangejia.bean.ImgBean;
import com.oracle.lingshangejia.bean.SignBean;
import com.oracle.lingshangejia.utils.AppManagerDelegate;
import com.oracle.lingshangejia.utils.FileUtil;
import com.oracle.lingshangejia.utils.MyLogger;
import com.oracle.lingshangejia.utils.MyToast;
import com.oracle.lingshangejia.utils.OkHttpUtils;
import com.oracle.lingshangejia.utils.SpUtils;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

//签约 身份证扫描界面
public class IdCardActivity extends BaseActivity implements View.OnClickListener {
    private LinearLayout ll_idcard_z,ll_idcard_f;//身份证正面,身份证反面
    private static final int REQUEST_CODE_CAMERA = 102;
    private static final int REQUEST_CODE_PICK_IMAGE_FRONT = 201; //正面
    private static final int REQUEST_CODE_PICK_IMAGE_BACK = 202;  //反面
    private static final int REQUEST_IMAGE = 200;
    private AlertDialog.Builder alertDialog;
    private ImageButton ib_back;
    private ImageView iv_zm_img,iv_fm_img;
    private RelativeLayout rl_idcard_ok;
    private TextView tv_idcard_num;
    private List<LocalMedia> selectList = new ArrayList<>();
    private String id_name="";
    private String id_cardid="";
    private String id_sex="";
    private String birthday = "";
    private String mImagePath = "";
    private String mImageId ="";

    @Override
    public int intiLayout() {
        return R.layout.activity_idcard;
    }

    @Override
    public void initView() {
        alertDialog = new AlertDialog.Builder(this);
        ll_idcard_z=findViewById(R.id.ll_idcard_z);
        tv_idcard_num=findViewById(R.id.tv_idcard_num);
        ll_idcard_f=findViewById(R.id.ll_idcard_f);
        iv_zm_img=findViewById(R.id.iv_zm_img);
        iv_fm_img=findViewById(R.id.iv_fm_img);
        ib_back=findViewById(R.id.ib_back);
        rl_idcard_ok=findViewById(R.id.rl_idcard_ok);
        ib_back.setOnClickListener(this);
        ll_idcard_z.setOnClickListener(this);
        ll_idcard_f.setOnClickListener(this);
        rl_idcard_ok.setOnClickListener(this);
    }

    @Override
    public void initData() {
        //  调用身份证扫描必须加上 intent.putExtra(CameraActivity.KEY_NATIVE_MANUAL, true); 关闭自动初始化和释放本地模型
        CameraNativeHelper.init(this, OCR.getInstance(this).getLicense(),
                new CameraNativeHelper.CameraNativeInitCallback() {
                    @Override
                    public void onError(int errorCode, Throwable e) {
                        String msg;
                        switch (errorCode) {
                            case CameraView.NATIVE_SOLOAD_FAIL:
                                msg = "加载so失败，请确保apk中存在ui部分的so";
                                break;
                            case CameraView.NATIVE_AUTH_FAIL:
                                msg = "授权本地质量控制token获取失败";
                                break;
                            case CameraView.NATIVE_INIT_FAIL:
                                msg = "本地质量控制";
                                break;
                            default:
                                msg = String.valueOf(errorCode);
                        }
                    }
                });
    }
    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.ll_idcard_z:  //正面
//                Intent intent = new Intent(IdCardActivity.this, CameraActivity.class);
//                intent.putExtra(CameraActivity.KEY_OUTPUT_FILE_PATH,
//                        FileUtil.getSaveFile(getApplication()).getAbsolutePath());
//                intent.putExtra(CameraActivity.KEY_CONTENT_TYPE, CameraActivity.CONTENT_TYPE_ID_CARD_FRONT);
//                startActivityForResult(intent, REQUEST_CODE_CAMERA);
                Intent intent = new Intent(this, CameraActivity.class);
                intent.putExtra(CameraActivity.KEY_OUTPUT_FILE_PATH,
                        FileUtil.getSaveFile(getApplication()).getAbsolutePath());
                intent.putExtra(CameraActivity.KEY_NATIVE_ENABLE,
                        true);
                // KEY_NATIVE_MANUAL设置了之后CameraActivity中不再自动初始化和释放模型
                // 请手动使用CameraNativeHelper初始化和释放模型
                // 推荐这样做，可以避免一些activity切换导致的不必要的异常
                intent.putExtra(CameraActivity.KEY_NATIVE_MANUAL,
                        true);
                intent.putExtra(CameraActivity.KEY_CONTENT_TYPE, CameraActivity.CONTENT_TYPE_ID_CARD_FRONT);
                startActivityForResult(intent, REQUEST_CODE_CAMERA);
                break;
            case R.id.ll_idcard_f: //反面 --》手持身份证照片
                // 进入相册 以下是例子：用不到的api可以不写
                PictureSelector.create(IdCardActivity.this)
                        .openGallery(PictureMimeType.ofImage())//全部.PictureMimeType.ofAll()、图片.ofImage()、视频.ofVideo()、音频.ofAudio()
                        .theme(R.style.picture_default_style)//主题样式(不设置为默认样式) 也可参考demo values/styles下 例如：R.style.picture.white.style
                        .maxSelectNum(1)// 最大图片选择数量 int
                        .minSelectNum(1)// 最小选择数量 int
                        .imageSpanCount(4)// 每行显示个数 int
                        .previewImage(true)// 是否可预览图片 true or false
                        .isCamera(true)// 是否显示拍照按钮 true or false
                        .imageFormat(PictureMimeType.PNG)// 拍照保存图片格式后缀,默认jpeg
                        .setOutputCameraPath("/CustomPath")// 自定义拍照保存路径,可不填
                        .withAspectRatio(1,1)
                        .enableCrop(true)// 是否裁剪 true or false
                        .compress(true)// 是否压缩 true or false
                        .compressSavePath(getPath())//压缩图片保存地址
                        .circleDimmedLayer(true)// 是否圆形裁剪 true or false
                        .previewEggs(false)// 预览图片时 是否增强左右滑动图片体验(图片滑动一半即可看到上一张是否选中) true or false
                        .minimumCompressSize(100)// 小于100kb的图片不压缩
                        .synOrAsy(true)//同步true或异步false 压缩 默认同步
                        .isDragFrame(false)// 是否可拖动裁剪框(固定)
                        .forResult(PictureConfig.CHOOSE_REQUEST);//结果回调onActivityResult code
                break;
            case R.id.ib_back:
                finish();
                break;
            case R.id.rl_idcard_ok: //身份证认证
                String idnumber= (String) SpUtils.get(IdCardActivity.this,"idnumber","");
                if(TextUtils.isEmpty(idnumber)||idnumber.equals("")){
                    Toast.makeText(IdCardActivity.this,"请先扫描身份证",Toast.LENGTH_SHORT).show();
                    return;
                }
                if (TextUtils.isEmpty(mImagePath)){
                    Toast.makeText(IdCardActivity.this,"请添手持身份证",Toast.LENGTH_SHORT).show();
                    return;
                }
                if (TextUtils.isEmpty(mImageId)){
                    Toast.makeText(IdCardActivity.this,"正在上传请稍后",Toast.LENGTH_SHORT).show();
                    return;
                }
                //判断是否添加手持身份证照片 （身份证正面照片 有身份证肯定是扫描过一定存在）
                getNetIdentify(idnumber);
                break;
        }
    }
    /**
     * 自定义压缩存储地址
     *
     * @return
     */
    private String getPath() {
        String path = Environment.getExternalStorageDirectory() + "/Luban/image/";
        File file = new File(path);
        if (file.mkdirs()) {
            return path;
        }
        return path;
    }
    /**
     * 身份证认证接口
     * @param idnumber  身份证号码
     */
    private void getNetIdentify(String idnumber) {
        //String token= (String) SpUtils.get(IdCardActivity.this,"token","");
        HashMap<Object, Object> map = new HashMap<>();
        map.put("sfzh",idnumber);
        OkHttpUtils.getNetWork(IdCardActivity.this, Constant.baseurl+"online/isSigning",map,handler);
        //idnumber
    }

    //签约
    private  void getNetToSign(int id,int ysid){
        HashMap<Object,Object> map = new HashMap<>();
        map.put("jmId",id);
        map.put("ysId",ysid);
        OkHttpUtils.getNetWork(IdCardActivity.this, Constant.baseurl+"online/signing",map,signhandler);
    }
    private Handler signhandler=new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what){
                case 1:  //成功S
                    String s= (String) msg.obj;
                    MyLogger.i("签约："+s);
                    Gson gson=new Gson();
                    SignBean bean=gson.fromJson(s, SignBean.class);
                    if(bean.getCode()==0){  //签约成功
                        Toast.makeText(IdCardActivity.this,bean.getMsg(),Toast.LENGTH_SHORT).show();
                       // AppManagerDelegate.getInstance().finishActivity(SignCstmrActivity.class);
                        AppManagerDelegate.getInstance().finishActivity(SignActivity.class);
                        AppManagerDelegate.getInstance().finishActivity(IdCardActivity.class);
                    }else if(bean.getCode()==1){  //签约失败
                        Toast.makeText(IdCardActivity.this,bean.getMsg(),Toast.LENGTH_SHORT).show();
                    }else{
                        Toast.makeText(IdCardActivity.this,bean.getMsg(),Toast.LENGTH_SHORT).show();
                    }
                    break;
                case 2: //连接上服务器，错误
                    String error= (String) msg.obj;
                    Toast.makeText(IdCardActivity.this,error,Toast.LENGTH_SHORT).show();
                    break;
                case 3:  //没有网络
                    Toast.makeText(IdCardActivity.this,"网络不可用",Toast.LENGTH_SHORT).show();
                    break;
                case 4: //没有连接上服务器
                    Toast.makeText(IdCardActivity.this,"连接服务器失败",Toast.LENGTH_SHORT).show();
                    break;
            }
        }
    };
    private Handler handler=new Handler(){
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what){
                case 1:  //成功S
                    String s= (String) msg.obj;
                    setData(s);
                    break;
                case 2: //连接上服务器，错误
                    String error= (String) msg.obj;
                    Toast.makeText(IdCardActivity.this,error,Toast.LENGTH_SHORT).show();
                    break;
                case 3:  //没有网络
                    Toast.makeText(IdCardActivity.this,"网络不可用",Toast.LENGTH_SHORT).show();
                    break;
                case 4: //没有连接上服务器
                    Toast.makeText(IdCardActivity.this,"连接服务器失败",Toast.LENGTH_SHORT).show();
                    break;
            }
        }
    };

    private void setData(String s){
        SpUtils.put(this,"idnumber","");
        MyLogger.i(s);
        Gson gson=new Gson();
        IdCardBean bean=gson.fromJson(s, IdCardBean.class);

        if(bean.getCode()==3){
//            if(bean.getData() ==null)
//            {
//                Toast.makeText(IdCardActivity.this,"未签约用户",Toast.LENGTH_SHORT).show();
//                return;

            Intent intent=new Intent(IdCardActivity.this, ArchivesActivity.class);
            intent.putExtra("shebao_name",id_name);
//            intent.putExtra("shebao_name",bean.getData().getXm());
            String sex="";
//            if(bean.getData().getXb()==1){
//                sex="男";
//            }else{
//                sex="女";
//            }
            if (!TextUtils.isEmpty(birthday)){
                intent.putExtra("birthday",birthday); //出生日期 新增加
            }
            intent.putExtra("shebao_sex",id_sex);
//            intent.putExtra("shebao_sex",sex);
            intent.putExtra("shebao_number",id_cardid);
            intent.putExtra("image", mImageId);//图片id手持
            intent.putExtra("sfqy",1);
            startActivity(intent);
        }else if(bean.getCode()==4){
           {  //未签约 (弹出签约对话框)
                //number name sex
                //String sex =id_sex;
               //基本信息以填 未签约
               MyToast.show("未签约 但已填基本信息code 4");
                showIdCardSignDialog(id_cardid,id_name,id_sex,bean.getData().getId());
               // showIdCardSignDialog(bean.getData().getSfzh(),bean.getData().getXm(),sex,bean.getData().getId());
            }
        }else if(bean.getCode()==2){
           {  //已签约 跳转首页
                Toast.makeText(IdCardActivity.this,"您已签约",Toast.LENGTH_SHORT).show();
                // AppManagerDelegate.getInstance().finishActivity(SignCstmrActivity.class);
                AppManagerDelegate.getInstance().finishActivity(SignActivity.class);
                AppManagerDelegate.getInstance().finishActivity(IdCardActivity.class);
            }
        }else if(bean.getCode()==10){  //token过期
            //AppManagerDelegate.getInstance().finishActivity(SignCstmrActivity.class);
            AppManagerDelegate.getInstance().finishActivity(SignActivity.class);
            AppManagerDelegate.getInstance().finishActivity(IdCardActivity.class);
            AppManagerDelegate.getInstance().finishActivity(MainActivity.class);
            SpUtils.put(IdCardActivity.this,"token","");
            SpUtils.put(IdCardActivity.this,"isLogin",false);
            Intent intent=new Intent(IdCardActivity.this,LoginActivity.class);
            startActivity(intent);
        }else{
            Toast.makeText(IdCardActivity.this,bean.getMsg(),Toast.LENGTH_SHORT).show();
        }
    }

    private void recIDCard(String idCardSide, final String filePath) {
        IDCardParams param = new IDCardParams();
        param.setImageFile(new File(filePath));
        // 设置身份证正反面
        param.setIdCardSide(idCardSide);
        // 设置方向检测
        param.setDetectDirection(true);
        // 设置图像参数压缩质量0-100, 越大图像质量越好但是请求时间越长。 不设置则默认值为20
        param.setImageQuality(15);

        OCR.getInstance(this).recognizeIDCard(param, new OnResultListener<IDCardResult>() {
            @Override
            public void onResult(IDCardResult result) {
                dismissLoading();
                if (result != null) {
                    Log.e("result",result.toString());
                    //alertText("", result.toString());
                    try{
                        if(result.getImageStatus().equals("non_idcard")||result.getImageStatus().equals("other_type_card")){
                            Toast.makeText(IdCardActivity.this,"请扫描正确的身份证",Toast.LENGTH_SHORT).show();
//                            Glide.with(IdCardActivity.this)
//                                    .load(R.drawable.ic_idsigning_id1)
//                                    .into(iv_zm_img);
                            tv_idcard_num.setVisibility(View.GONE);
                        }else{
                            //设置图片
                            tv_idcard_num.setVisibility(View.VISIBLE);


//                            Glide.with(IdCardActivity.this)
//                                    .load(filePath)
//                                    .into(iv_zm_img);
                            birthday = result.getBirthday().toString();
                            showTestIdNumberDialog(result.getIdNumber().toString(),result.getName().toString(),result.getGender().toString());
                        }
                    }catch (Exception e){
                        e.printStackTrace();
                    }
                }
            }

            @Override
            public void onError(OCRError error) {
                dismissLoading();
                alertText("网络错误", error.getMessage());
            }
        });
    }

    @Override
    protected void onResume() {
        super.onResume();
        //tv_idcard_num.setVisibility(View.GONE);
    }

    private void alertText(final String title, final String message) {
        this.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                alertDialog.setTitle(title)
                        .setMessage(message)
                        .setPositiveButton("确定", null)
                        .show();
            }
        });
    }
    private String getRealPathFromURI(Uri contentURI) {
        String result;
        Cursor cursor = getContentResolver().query(contentURI, null, null, null, null);
        if (cursor == null) { // Source is Dropbox or other similar local file path
            result = contentURI.getPath();
        } else {
            cursor.moveToFirst();
            int idx = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA);
            result = cursor.getString(idx);
            cursor.close();
        }
        return result;
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (requestCode == REQUEST_CODE_PICK_IMAGE_FRONT && resultCode == Activity.RESULT_OK) {
            showLoading();
            Uri uri = data.getData();
            String filePath = getRealPathFromURI(uri);
            recIDCard(IDCardParams.ID_CARD_SIDE_FRONT, filePath);
        }

        if (requestCode == REQUEST_CODE_PICK_IMAGE_BACK && resultCode == Activity.RESULT_OK) {
            showLoading();
            Uri uri = data.getData();
            String filePath = getRealPathFromURI(uri);
            recIDCard(IDCardParams.ID_CARD_SIDE_BACK, filePath);
        }
        if (requestCode == REQUEST_CODE_CAMERA && resultCode == Activity.RESULT_OK) {
            showLoading();
            if (data != null) {
                String contentType = data.getStringExtra(CameraActivity.KEY_CONTENT_TYPE);
                String filePath = FileUtil.getSaveFile(getApplicationContext()).getAbsolutePath();
                if (!TextUtils.isEmpty(contentType)) {
                    if (CameraActivity.CONTENT_TYPE_ID_CARD_FRONT.equals(contentType)) {
                        recIDCard(IDCardParams.ID_CARD_SIDE_FRONT, filePath);
                    } else if (CameraActivity.CONTENT_TYPE_ID_CARD_BACK.equals(contentType)) {
                        recIDCard(IDCardParams.ID_CARD_SIDE_BACK, filePath);
                    }
                }
            }
        }

        if (requestCode == PictureConfig.CHOOSE_REQUEST && resultCode == RESULT_OK){
            showLoading();
            // 图片选择结果回调
            selectList = PictureSelector.obtainMultipleResult(data);

            // 例如 LocalMedia 里面返回三种path
            // 1.media.getPath(); 为原图path
            // 2.media.getCutPath();为裁剪后path，需判断media.isCut();是否为true
            // 3.media.getCompressPath();为压缩后path，需判断media.isCompressed();是否为true
            // 如果裁剪并压缩了，已取压缩路径为准，因为是先裁剪后压缩的
            File file = null;
            for (LocalMedia media : selectList) {
                Log.i("图片-----》", media.getPath());
                mImagePath = media.getPath();
               file = new File(media.getCutPath());
                //设置图片
                Glide.with(IdCardActivity.this)
                        .load(file.getPath())
                        .into(iv_fm_img);


            }

             List<File> files = new ArrayList<>();
             files.add(file);
             OkGo.<String>post(Constant.baseurl+"open/uploadImg")
                    .tag(this)//
                    .isMultipart(true)
                    .addFileParams("files",files).execute(new StringCallback() {
                @Override
                public void onSuccess(Response<String> response) {
                    Gson gson=new Gson();
                    ImgBean bean=gson.fromJson(response.body(),ImgBean.class);
                    if (bean.getCode() == 0){
                        //图片上成功 获取图片id
                        mImageId = Integer.toString(bean.getFileUrl().get(0)) ;
                        dismissLoading();
                    }


                }

                 @Override
                 public void onError(Response<String> response) {
                     super.onError(response);
                     dismissLoading();
                     Toast.makeText(IdCardActivity.this,"网络错误",Toast.LENGTH_SHORT).show();
                 }
             });


        }


    }
    @Override
    protected void onDestroy() {
        // 释放本地质量控制模型
        CameraNativeHelper.release();
        super.onDestroy();
    }

    /**
     *
     * 弹出检查身份证号是否正确对话框
     * @param number  身份证号
     * @param name  姓名
     * @param sex  性别
     */
    private void showTestIdNumberDialog(final String number, String name, String sex){
        final Dialog dialog = new Dialog(this, R.style.dialog);
        View view_dialog = LayoutInflater.from(this).inflate(
                R.layout.testidnumber_dialog, null);
        TextView tv_test_name=view_dialog.findViewById(R.id.tv_test_name);
        TextView tv_test_sex=view_dialog.findViewById(R.id.tv_test_sex);
        TextView tv_test_number=view_dialog.findViewById(R.id.tv_test_number);
        TextView tv_test_cancle=view_dialog.findViewById(R.id.tv_test_cancle);
        TextView tv_test_ok=view_dialog.findViewById(R.id.tv_test_ok);
        if(!TextUtils.isEmpty(number))
        id_cardid = number;
        if(!TextUtils.isEmpty(name))
        id_name = name;
        if(!TextUtils.isEmpty(sex))
        id_sex = sex;
        tv_test_name.setText("姓名："+name);
        tv_test_sex.setText("性别："+sex);
        tv_test_number.setText("身份证号："+number);
        tv_test_cancle.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
            }
        });
        tv_test_ok.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
               SpUtils.put(IdCardActivity.this,"idnumber",number);
               dialog.dismiss();
            }
        });
        dialog.setContentView(view_dialog);
        Window dialogWindow = dialog.getWindow();
        //设置位置
        dialogWindow.setGravity(Gravity.CENTER);
        //设置dialog的宽高属性
        dialogWindow.setLayout(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        dialog.show();
    }

    /**
     * 弹出签约对话框
     */
    private void showIdCardSignDialog(final String number, String name, String sex, final int id){
        final Dialog dialog = new Dialog(this, R.style.dialog);
        View view_dialog = LayoutInflater.from(this).inflate(
                R.layout.idcardsign_dialog, null);
        TextView tv_sign_name=view_dialog.findViewById(R.id.tv_sign_name);
        TextView tv_sign_sex=view_dialog.findViewById(R.id.tv_sign_sex);
        TextView tv_sign_number=view_dialog.findViewById(R.id.tv_sign_number);
        TextView tv_sign_cancle=view_dialog.findViewById(R.id.tv_sign_cancle);
        TextView tv_sign_ok=view_dialog.findViewById(R.id.tv_sign_ok);
        tv_sign_cancle.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
            }
        });
        tv_sign_ok.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //签约接口
                int ysid= (int) SpUtils.get(IdCardActivity.this,"ysid",-1);
                getNetToSign(id,ysid);
            }
        });
        tv_sign_name.setText("姓名："+name);
        tv_sign_sex.setText("性别："+sex);
        tv_sign_number.setText("身份证号："+number);
        dialog.setContentView(view_dialog);
        Window dialogWindow = dialog.getWindow();
        //设置位置
        dialogWindow.setGravity(Gravity.CENTER);
        //设置dialog的宽高属性
        dialogWindow.setLayout(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        dialog.show();
    }
}
